<template>
  <div class="profile-container">
    <!-- 用户头像和基本信息区域 -->
    <el-card class="profile-header-card">
      <div class="profile-header">
        <div class="avatar-section">
          <el-avatar :size="80" class="user-avatar">
            <el-icon><User /></el-icon>
          </el-avatar>
                      <div class="user-basic-info">
              <h2 class="user-name">{{ userInfo.username }}</h2>
              <p class="user-title">{{ userInfo.worktype }} · {{ userInfo.department }}</p>
            <p class="user-status">
              <el-tag :type="userInfo.status === 'active' ? 'success' : 'danger'" size="small">
                {{ userInfo.status === 'active' ? '在线' : '离线' }}
              </el-tag>
            </p>
          </div>
        </div>
        <div class="quick-actions">
          <el-button type="primary" @click="editMode = !editMode" v-if="!editMode">
            <el-icon><Edit /></el-icon>
            编辑资料
          </el-button>
          <div v-else class="edit-actions">
            <el-button type="success" @click="saveProfile" :loading="saving">
              <el-icon><Check /></el-icon>
              保存
            </el-button>
            <el-button @click="cancelEdit">
              <el-icon><Close /></el-icon>
              取消
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <el-row :gutter="24" class="profile-content">
      <!-- 个人信息卡片 -->
      <el-col :span="16">
        <el-card class="profile-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">
                <el-icon><UserFilled /></el-icon>
                个人信息
              </span>
            </div>
          </template>
          
          <el-form 
            :model="userInfo" 
            :rules="profileRules" 
            ref="profileFormRef" 
            label-width="100px"
            :disabled="!editMode"
            class="profile-form"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="userInfo.username" disabled>
                    <template #prefix>
                      <el-icon><User /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户类型" prop="userType">
                  <el-select v-model="userInfo.userType" placeholder="请选择用户类型" :disabled="!editMode">
                    <el-option label="普通账户" value="普通账户" />
                    <el-option label="管理员" value="管理员" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="工作职责" prop="worktype">
                  <el-input v-model="userInfo.worktype" placeholder="请输入工作职责">
                    <template #prefix>
                      <el-icon><Briefcase /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="部门" prop="department">
                  <el-input v-model="userInfo.department" placeholder="请输入所属部门">
                    <template #prefix>
                      <el-icon><OfficeBuilding /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="备注" prop="remark">
              <el-input 
                v-model="userInfo.remark" 
                type="textarea" 
                :rows="4"
                placeholder="请输入备注信息"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      
      <!-- 右侧信息区域 -->
      <el-col :span="8">
        <!-- 修改密码卡片 -->
        <el-card class="password-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">
                <el-icon><Lock /></el-icon>
                修改密码
              </span>
            </div>
          </template>
          
          <el-form 
            :model="passwordForm" 
            :rules="passwordRules" 
            ref="passwordFormRef" 
            label-width="100px"
            class="password-form"
          >
            <el-form-item label="当前密码" prop="currentPassword">
              <el-input 
                v-model="passwordForm.currentPassword" 
                type="password" 
                placeholder="请输入当前密码"
                show-password
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input 
                v-model="passwordForm.newPassword" 
                type="password" 
                placeholder="请输入新密码"
                show-password
              >
                <template #prefix>
                  <el-icon><Key /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input 
                v-model="passwordForm.confirmPassword" 
                type="password" 
                placeholder="请再次输入新密码"
                show-password
              >
                <template #prefix>
                  <el-icon><Key /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item>
              <el-button 
                type="primary" 
                @click="changePassword" 
                :loading="changingPassword"
                style="width: 100%"
              >
                <el-icon><Check /></el-icon>
                修改密码
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
        
        <!-- 账户信息卡片 -->
        <el-card class="account-card" shadow="hover" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span class="card-title">
                <el-icon><InfoFilled /></el-icon>
                账户信息
              </span>
            </div>
          </template>
          
          <div class="account-info">
            <div class="info-item">
              <div class="info-label">
                <el-icon><User /></el-icon>
                <span>用户ID</span>
              </div>
              <span class="info-value">{{ userInfo.id || '未知' }}</span>
            </div>
            <div class="info-item">
              <div class="info-label">
                <el-icon><Calendar /></el-icon>
                <span>注册时间</span>
              </div>
              <span class="info-value">{{ formatDate(userInfo.createTime) }}</span>
            </div>
            <div class="info-item">
              <div class="info-label">
                <el-icon><Clock /></el-icon>
                <span>最后登录</span>
              </div>
              <span class="info-value">{{ formatDate(userInfo.lastLoginTime) }}</span>
            </div>
            <div class="info-item">
              <div class="info-label">
                <el-icon><CircleCheck /></el-icon>
                <span>账户状态</span>
              </div>
              <el-tag :type="userInfo.status === 'active' ? 'success' : 'danger'" size="small">
                {{ userInfo.status === 'active' ? '正常' : '禁用' }}
              </el-tag>
            </div>
            <div class="info-item">
              <div class="info-label">
                <el-icon><Location /></el-icon>
                <span>登录IP</span>
              </div>
              <span class="info-value">{{ userInfo.lastLoginIp || '未知' }}</span>
            </div>
            <div class="info-item">
              <div class="info-label">
                <el-icon><Monitor /></el-icon>
                <span>登录设备</span>
              </div>
              <span class="info-value">{{ userInfo.lastLoginDevice || '未知' }}</span>
            </div>
          </div>
        </el-card> 
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Edit, Check, Close, User, UserFilled, Message, Phone, 
  OfficeBuilding, Briefcase, Lock, Key, InfoFilled, 
  Calendar, Clock, CircleCheck, Location, Monitor, DataLine 
} from '@element-plus/icons-vue'
import { getUserById, updateUser } from '../api/user'
import { verifyPassword } from '../utils/crypto'

// 响应式数据
const editMode = ref(false)
const saving = ref(false)
const changingPassword = ref(false)
const profileFormRef = ref()
const passwordFormRef = ref()

// 用户信息
const userInfo = reactive({
  id: '',
  username: '',
  userType: '',
  worktype: '',
  department: '',
  remark: '',
  createTime: '',
  lastLoginTime: '',
  lastLoginIp: '',
  lastLoginDevice: '',
  status: 'active'
})

// 用户统计信息
const userStats = reactive({
  projectCount: 0,
  taskCount: 0,
  loginDays: 0,
  onlineHours: 0
})

// 密码表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const profileRules = {
  userType: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ],
  worktype: [
    { required: true, message: '请输入工作职责', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请输入所属部门', trigger: 'blur' }
  ]
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户信息
const loadUserInfo = async () => {
  try {
    const currentUser = JSON.parse(localStorage.getItem('user'))
    if (!currentUser) {
      ElMessage.error('用户信息不存在，请重新登录')
      return
    }
    
    // 获取最新的用户信息
    const response = await getUserById(currentUser.id)
    console.log(response);
    const userData = response
    
    // 更新用户信息
    Object.assign(userInfo, {
      id: userData.id || userData.Id,
      username: userData.Username || userData.username || '',
      userType: userData.userType || userData.UserType || '',
      worktype: userData.worktype || userData.Worktype || '',
      department: userData.departement || userData.Departement || userData.department || userData.Department || '',
      remark: userData.remark || userData.Remark || '',
      createTime: userData.CreateTime || userData.createTime || userData.createdAt || '',
      lastLoginTime: userData.LastLoginTime || userData.lastLoginTime || userData.lastLogin || '',
      lastLoginIp: userData.LastLoginIp || userData.lastLoginIp || userData.loginIp || '',
      lastLoginDevice: userData.LastLoginDevice || userData.lastLoginDevice || userData.device || '',
      status: userData.Status || userData.status || 'active'
    })
    
    // 模拟用户统计数据
    userStats.projectCount = Math.floor(Math.random() * 20) + 5
    userStats.taskCount = Math.floor(Math.random() * 100) + 20
    userStats.loginDays = Math.floor(Math.random() * 365) + 30
    userStats.onlineHours = Math.floor(Math.random() * 1000) + 100
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 保存个人信息
const saveProfile = async () => {
  try {
    await profileFormRef.value.validate()
    saving.value = true
    
    const updateData = {
      realName: userInfo.realName,
      email: userInfo.email,
      phone: userInfo.phone,
      department: userInfo.department,
      position: userInfo.position,
      bio: userInfo.bio
    }
    
    await updateUser(userInfo.id, updateData)
    
    // 更新本地存储的用户信息
    const currentUser = JSON.parse(localStorage.getItem('user'))
    const updatedUser = { ...currentUser, ...updateData }
    localStorage.setItem('user', JSON.stringify(updatedUser))
    
    ElMessage.success('个人信息保存成功')
    editMode.value = false
  } catch (error) {
    console.error('保存个人信息失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    saving.value = false
  }
}

// 取消编辑
const cancelEdit = () => {
  editMode.value = false
  // 重新加载用户信息，恢复原始数据
  loadUserInfo()
}

// 修改密码
const changePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    changingPassword.value = true
    
    // 验证当前密码
    const currentUser = JSON.parse(localStorage.getItem('user'))
    if (!verifyPassword(passwordForm.currentPassword, currentUser.password)) {
      ElMessage.error('当前密码错误')
      return
    }
    
    // 更新密码
    await updateUser(userInfo.id, { password: passwordForm.newPassword })
    
    // 更新本地存储的用户密码
    currentUser.password = passwordForm.newPassword
    localStorage.setItem('user', JSON.stringify(currentUser))
    
    ElMessage.success('密码修改成功')
    
    // 清空密码表单
    passwordForm.currentPassword = ''
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''
    passwordFormRef.value.resetFields()
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败，请重试')
  } finally {
    changingPassword.value = false
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 组件挂载时加载用户信息
onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
.profile-container {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

.profile-header-card {
  margin-bottom: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: 4px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.user-basic-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.user-name {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
}

.user-title {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

.user-status {
  margin: 0;
}

.quick-actions {
  display: flex;
  gap: 12px;
}

.edit-actions {
  display: flex;
  gap: 12px;
}

.profile-content {
  margin-top: 24px;
}

.profile-card,
.password-card,
.account-card,
.stats-card {
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.profile-card:hover,
.password-card:hover,
.account-card:hover,
.stats-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.profile-form,
.password-form {
  padding: 20px 0;
}

.account-info {
  padding: 20px 0;
}

.account-info .info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.account-info .info-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.info-label {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 14px;
}

.info-value {
  color: #333;
  font-weight: 500;
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  padding: 20px 0;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  opacity: 0.9;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #2c3e50;
}

:deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: #f8f9fa;
}

:deep(.el-card__header) {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-bottom: 1px solid #e9ecef;
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
}
</style> 